import http from "@/utils/request";
const modulesFiles = require.context("./modules", true, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});

let Api = {};
//合并所以api
Object.keys(modules).forEach((item) => {
  Object.assign(Api, modules[item]);
});
//批量创建请求
const injectRequest = (apis) => {
  const request = {};
  Object.keys(apis).forEach((item) => {
    const { method, url } = apis[item];
    request[item] = (dataOrParams = {}) => {
      method = method.toUpperCase();
      const key = ["PUT", "POST", "PATCH"].includes(method) ? "data" : "params";
      return http({
        method,
        url,
        [key]: dataOrParams,
      });
    };
  });
  return request;
};

module.exports = injectRequest(Api);
